<?php
// +----------------------------------------------------------------------
// | ManniuRead
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2016 http://manniuyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: heitao <read@manniuyun.com>
// +----------------------------------------------------------------------

/**
 * 文件上传类
 */

namespace app\api\controller;

use manniu\controller\Base;

class Upload extends Base
{
    /**
     * 初始化
     */
    public function _initialize()
    {
        parent::_initialize();
        if (!$this->uid && !$this->aid) {
            $this->error('请登录后再执行相关操作', '/');
        }
    }

    /**
     * 百度文件上传组件 - WebUploader
     * @access public
     * @return \think\Response
     */
    public function webUploader()
    {
        $is_image = (int)$this->request->param('is_image');
        // 上传路径
        $path = '';
        if ($is_image) {
            $size = 2; // 表示2M
            $ext = 'jpg,png,gif'; // 图片后缀
        } else {
            $size = 5; // 表示5M
            $ext = 'rar,zip'; // 文件后缀
        }

        $this->assign([
            'size' => $size,
            'extensions' => $ext,
            'path' => $path
        ]);
        return $this->fetch();
    }

    /**
     * ajax文件上传
     */
    public function ajaxUpload()
    {
        $is_image = (int)$this->request->param('is_image');
        if ($is_image) {
            $size = 2 * 1024 * 1024; // 单位字节
            $ext = 'jpg,png,gif'; // 图片后缀
        } else {
            $size = 5 * 1024 * 1024; // 表示5M
            $ext = 'rar,zip'; // 文件后缀
        }

        // 获取表单上传文件
        $file = $this->request->file('file');
        if (empty($file)) {
            return json(['status' => 0, 'code' => '请选择上传文件']);
        }

        // 移动到上传目录
        $info = $file->validate(['size' => $size, 'ext' => $ext])->move(config('mn_public.upload_path'), true, false);
        if ($info) {
            // 拼接url路径
            $filepath = str_replace('\\', '/', config('mn_public.upload_path') . $info->getSaveName());
            $file_url = str_replace(ROOT_PATH . 'public', '', $filepath);
            return json(['status' => 1, 'code' => ['filepath' => $file_url, 'msg' => '上传成功']]);
        } else {
            // 上传失败获取错误信息
            return json(['status' => 0, 'code' => $file->getError()]);
        }
    }
}